# -*- coding:utf-8 -*-

import sys
import sqlite3
import os
import time
import threading
sys.path.append('./python3/lib')
from flask import Flask, request, redirect, abort, render_template, url_for
from flask_bootstrap import Bootstrap

app = Flask(__name__)
bootstrap = Bootstrap(app)


os.environ['GIT_PYTHON_GIT_EXECUTABLE'] = 'C:/Program Files/Git/cmd/git.exe'

@app.route('/pml/', methods=['GET'])
def index():
    logs = get_log_data()
    if is_lock():
        return render_template('index.html', table=logs, user=get_last_ip())
    else:
        return render_template('index.html', table=logs)


@app.route('/pml/pull', methods=['GET'])
def pull():
    logs = get_log_data()
    if is_lock():
        return render_template('index.html', table=logs, user=get_last_ip())
    else:
        if request.headers.getlist("X-Forwarded-For"):
            ip = request.headers.getlist("X-Forwarded-For")[0]
        else:
            ip = request.remote_addr
        log_data(ip,
                 time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
        t = threading.Thread(target=git_pull)
        t.start()
        return redirect(url_for('index'), code=302)


@app.errorhandler(404)
def page_not_found(e):
    return redirect(url_for('index'), code=302)


def init_db():
    """
    初始化日志db
    用于储存 git pull 日期、IP地址等信息
    """
    conn = sqlite3.connect(logdb)
    cursor = conn.cursor()
    cursor.execute("""
    CREATE TABLE
    IF NOT EXISTS lock(
    id integer PRIMARY KEY,
    islock integer DEFAULT 0
    );
    """)
    cursor.execute('INSERT INTO lock (islock) VALUES (0)')
    cursor.execute("""
    CREATE TABLE
    IF NOT EXISTS pull_log (
    id integer PRIMARY KEY,
    pull_date text NOT NULL,
    pull_ip text NOT NULL
    );
    """)
    cursor.close()
    conn.commit()
    conn.close()


def is_lock():
    """
    检查 lock表中islock状态，返回是否lock
    """
    conn = sqlite3.connect(logdb)
    cursor = conn.cursor()
    cursor.execute('SELECT islock FROM lock WHERE id = 1')
    result = cursor.fetchall()[0][0]
    cursor.close()
    conn.close()
    return result


def set_lock(flag):
    """
    设置lock表中 islock状态，0 或者 1
    """
    conn = sqlite3.connect(logdb)
    cursor = conn.cursor()
    cursor.execute('UPDATE lock SET islock = (?) WHERE id = 1', (flag, ))
    conn.commit()
    cursor.close()
    conn.close()


def log_data(pull_ip, pull_date):
    """
    记录更新仓库的ip地址和时间
    """
    conn = sqlite3.connect(logdb)
    cursor = conn.cursor()
    cursor.execute('INSERT INTO pull_log (pull_ip,pull_date) values (?,?)',
                   (pull_ip, pull_date))
    conn.commit()
    cursor.close()
    conn.close()


def get_log_data():
    """
    获取最近10条更新记录
    """
    conn = sqlite3.connect(logdb)
    cursor = conn.cursor()
    cursor.execute(
        'SELECT pull_ip,pull_date FROM pull_log ORDER BY id DESC LIMIT 30')
    result = cursor.fetchall()
    cursor.close()
    conn.close()
    return result


def get_last_ip():
    """
    获取最近一条IP
    """
    conn = sqlite3.connect(logdb)
    cursor = conn.cursor()
    cursor.execute('SELECT pull_ip FROM pull_log ORDER BY id DESC LIMIT 1')
    result = cursor.fetchall()[0][0]
    cursor.close()
    conn.close()
    return result


def git_pull():
    """
    使用python 更新git仓库
    """
    set_lock(1)
    try:
        import git
        #g = git.cmd.Git(repo)
        #g.pull()

        r = git.Repo(repo)
        for remote in r.remotes:
            remote.fetch()
        r.git.reset('--hard','origin/master')
    except Exception as e:
        print(e)
    finally:
        set_lock(0)


def monitor_template():
    from os import path
    extra_dirs = ['templates',]
    extra_files = extra_dirs[:]
    for extra_dir in extra_dirs:
        for dirname, dirs, files in os.walk(extra_dir):
            for filename in files:
                filename = path.join(dirname, filename)
                if path.isfile(filename):
                    extra_files.append(filename)
    return extra_files


if __name__ == '__main__':
    logdb = 'log.db'
    #repo = '~/sb'
    repo = 'D:/version_control/pmllib'

    if not os.path.exists(logdb):
        init_db()
    app.run(host='127.0.0.1', port=8000, debug=True, threaded=True, extra_files=monitor_template())
